package org.myrpc.server;

import java.awt.List;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.I0Itec.zkclient.ZkClient;
import org.myrpc.rpc.rpc;


public class RpcServer extends Thread{
	private int port;
	private String address;
	
	public RpcServer(int port, String address) {
		this.port = port;
		this.address = address;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}
	
	@Override
	public void run() {
		//启动服务
		startServerSocket();
	}
	
	/*
	 * 启动服务
	 * */
	public void startServerSocket() {//端口号，和报名（多个用逗号分隔）
		ServerSocket serverSocket = null;
		ThreadPoolExecutor executor = null;
		try {
			serverSocket = new ServerSocket(port);
			//注册服务
			register();
			
			executor = new ThreadPoolExecutor(5, 10, 100, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
			while(true) {
				//阻塞等待客户端连接
				Socket socket = serverSocket.accept();
				executor.execute(new RpcServiceRunable(socket));
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				serverSocket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				serverSocket=null;
			}finally {
				if(executor!=null) {
					executor.shutdown();
				}
			}
		}
	}
	
	
	private void register() {
		ZkClient client = new ZkClient(address, 30000, 1000);
		String path = "/myrpc";//自定义节点头
		if(!client.exists(path)) {//不存在节点就创建
			client.createPersistent(path);
		}
		InetAddress ipAddress;
		try {
			ipAddress = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException("获取本机地址失败");
		}
		String ip = ipAddress.getHostAddress();
		String service = ip+":"+port;
		path = path+"/"+service;
		if(client.exists(path)) {//创建过节点就删除
			client.delete(path);
		}
		//创建节点
		client.createEphemeral(path, service);
		
	}
	
}
